C++20 introduces two standard attributes to indicate the likelihood of a branch: [[likely]]
and [[unlikely]]
.
These attributes replace the non-standard built-in __builtin_expect
supported by Clang and GCC that was mostly used as part of
likely()
and unlikely()
macros.
The standard annotations should always be preferred because they make the code portable and future-proof.
This rule reports the direct use of __builtin_expect
built-in and its indirect use through likely()
and
unlikely()
macros.
Noncompliant code example
if (likely(!v.empty())) { // Noncompliant
std::cout <<v[0] <<'\n';
}
if (unlikely(nullptr == ptr)) { // Noncompliant
std::cerr <<"Unexpected null pointer\n";
exit(0);
}
Compliant solution
if (!v.empty()) [[likely]] {
std::cout <<v[0] <<'\n';
}
if (nullptr == ptr) [[unlikely]] {
std::cerr <<"Unexpected null pointer\n";
exit(0);
}